<?php

namespace app\index\validate;

use think\Validate;
use think\Db;

/**
 * goods验证器
 */
class Goods extends Validate
{

    protected $rule = [
        'area'
            => 'require|in:1,2',
        'type'
            => 'require|in:1,2',
        'bargain'
            => 'require|in:0,1,2',
        'title|货物名称'
            => 'require|min:2|max:36',
        'price|标价'
            => 'require|max:4|between:0,10000|number',
        'cate_id'
            => 'require|number|exists:goods_category,cate_id',
        'deadline|上架期限'
            => 'require|between:3,180|number',
        'examine_reason' => 'require|max:50',
    ];

    protected $message = [
        'title.max'         => '名字不宜过长，12个汉字内适宜',
        'price.between'     => '别搞笑',
        'price.max'         => '不接受万元以上物品',
        'price.number'      => '标价只接受整数',
        'deadline.between'  => '上架期限只允许3~180天',
        'deadline.number'   => '上架期限只接受整数',
        'examine_reason.require'   => '请说明理由',
        'examine_reason.max'   => '理由最多50个字',
    ];

    protected $scene = [
        'not_through' => 'examine_reason',
        'not_sell' => 'examine_reason',
        'add' => 'area,type,bargain,title,price,cate_id,deadline',
    ];
    // 自定义exists规则，exists:table,字段,排除的某个值  即若验证的值与排除的值相等则返回true
    protected function exists($value, $rule, $data, $field)
    {
        if (is_string($rule)) {
            $rule = explode(',', $rule);
        }
        if (isset($rule[2]) && $value == $rule[2]) {
            return true;
        }
        $db = Db::name($rule[0]);
        $key = isset($rule[1]) ? $rule[1] : $field;
        if (strpos($key, '^')) {
            // 支持多个字段验证
            $fields = explode('^', $key);
            foreach ($fields as $key) {
                $map[$key] = $data[$key];
            }
        } elseif (strpos($key, '=')) {
            parse_str($key, $map);
        } else {
            $map[$key] = $data[$field];
        }
        if ($db->where($map)->find()) {
            return true;
        }
        return false;
    }

}
